package net.netty.heart;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 王霄
 * @date 2021/9/8 10:40
 **/
public class HeartHandle extends ChannelInboundHandlerAdapter {

    private static final DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        LocalDateTime now = LocalDateTime.now();
        if (evt instanceof IdleStateEvent event) {
            //将  evt 向下转型 IdleStateEvent
            switch (event.state()) {
                case READER_IDLE -> System.out.println(String.format("发生读空闲事件,time:%s", df.format(now)));
                //case WRITER_IDLE -> System.out.println("写空闲");
                //case ALL_IDLE -> System.out.println("读写空闲");
            }
            ;
            //如果发生空闲，我们关闭通道
            // ctx.channel().close();
        }
    }
}
